"""
检查所有ISIC 2018实验的训练状态
"""

import os
import pandas as pd
from pathlib import Path
from datetime import datetime

def check_model_status(model_name):
    """检查单个模型的训练状态"""
    
    model_dir = f"models/{model_name}"
    
    if not os.path.exists(model_dir):
        return {
            "model": model_name,
            "status": "❌ 未开始",
            "epochs": 0,
            "best_iou": 0,
            "best_epoch": 0,
        }
    
    log_file = f"{model_dir}/log.csv"
    
    if not os.path.exists(log_file):
        return {
            "model": model_name,
            "status": "⚠️ 已创建目录但无日志",
            "epochs": 0,
            "best_iou": 0,
            "best_epoch": 0,
        }
    
    try:
        df = pd.read_csv(log_file)
        
        if len(df) == 0:
            return {
                "model": model_name,
                "status": "⚠️ 日志为空",
                "epochs": 0,
                "best_iou": 0,
                "best_epoch": 0,
            }
        
        current_epoch = len(df)
        best_iou = df['val_iou'].max()
        best_epoch = df['val_iou'].idxmax() + 1
        
        # 检查是否完成
        config_file = f"{model_dir}/config.yml"
        total_epochs = 150  # 默认值
        
        if os.path.exists(config_file):
            import yaml
            with open(config_file, 'r') as f:
                config = yaml.safe_load(f)
                total_epochs = config.get('epochs', 150)
        
        if current_epoch >= total_epochs:
            status = "✅ 已完成"
        else:
            progress = (current_epoch / total_epochs) * 100
            status = f"🔄 训练中 ({current_epoch}/{total_epochs}, {progress:.1f}%)"
        
        return {
            "model": model_name,
            "status": status,
            "epochs": current_epoch,
            "best_iou": best_iou,
            "best_epoch": best_epoch,
            "latest_loss": df['val_loss'].iloc[-1],
            "latest_iou": df['val_iou'].iloc[-1],
        }
        
    except Exception as e:
        return {
            "model": model_name,
            "status": f"⚠️ 读取错误: {str(e)}",
            "epochs": 0,
            "best_iou": 0,
            "best_epoch": 0,
        }


def main():
    """主函数"""
    
    models = [
        "ISIC2018_UNet_Baseline",
        "ISIC2018_NestedUNet_Baseline",
        "ISIC2018_NestedUNet_DeepSup",
        "ISIC2018_EnhancedUNet",
        "ISIC2018_EnhancedUNet_DeepSup",
    ]
    
    print("="*90)
    print("ISIC 2018 实验训练状态")
    print(f"检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*90)
    print()
    
    results = []
    
    for model_name in models:
        result = check_model_status(model_name)
        results.append(result)
    
    # 打印表格
    print(f"{'模型':<40} {'状态':<30} {'最佳IoU':<12} {'当前IoU':<12}")
    print("-"*90)
    
    for r in results:
        model_short = r['model'].replace('ISIC2018_', '')
        status = r['status']
        best_iou = f"{r['best_iou']:.4f}" if r['best_iou'] > 0 else "N/A"
        latest_iou = f"{r.get('latest_iou', 0):.4f}" if r.get('latest_iou', 0) > 0 else "N/A"
        
        print(f"{model_short:<40} {status:<30} {best_iou:<12} {latest_iou:<12}")
    
    print()
    print("="*90)
    
    # 统计信息
    completed = sum(1 for r in results if "完成" in r['status'])
    training = sum(1 for r in results if "训练中" in r['status'])
    not_started = sum(1 for r in results if "未开始" in r['status'])
    
    print(f"统计: ✅ 已完成 {completed} | 🔄 训练中 {training} | ❌ 未开始 {not_started}")
    
    # 找出最佳模型
    valid_results = [r for r in results if r['best_iou'] > 0]
    if valid_results:
        best = max(valid_results, key=lambda x: x['best_iou'])
        print(f"\n当前最佳: {best['model'].replace('ISIC2018_', '')}")
        print(f"  - Best Val IoU: {best['best_iou']:.4f} (Epoch {best['best_epoch']})")
    
    print("\n提示:")
    print("  - 运行 'python quick_train_baseline.py' 训练Baseline模型")
    print("  - 运行 'python evaluate_all.py' 评估所有已完成的模型")
    print("  - 运行 'python visualize_results.py' 生成可视化结果")
    print()


if __name__ == "__main__":
    main()






